<template>
    <!-- 集采汇总编辑页 -->
    <div class="e-form">
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="汇总明细"
                    name="planDetail"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="basicForm"
                                        :rules="rules"
                                        ref="basicForm"
                                        class="demo-ruleForm"
                                        label-width="150px"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="计划编号："
                                                >
                                                    <span>{{
                                                        basicForm.billNo
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="单据机构："
                                                >
                                                    <span>{{
                                                        basicForm.orgName
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="计划金额："
                                                >
                                                    <span>{{
                                                        basicForm.amount
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="汇总日期："
                                                    prop="summaryDate"
                                                >
                                                    <el-date-picker
                                                        type="date"
                                                        placeholder="选择日期"
                                                        v-model="
                                                            basicForm.summaryDate
                                                        "
                                                    ></el-date-picker>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="币种："
                                                    prop="currencyId"
                                                >
                                                    <el-select
                                                        v-model="
                                                            basicForm.currencyId
                                                        "
                                                        placeholder="请选择"
                                                        @change="currencyChange"
                                                    >
                                                        <el-option
                                                            v-for="item in currencyForm"
                                                            :key="item.value"
                                                            :label="item.label"
                                                            :value="item.value"
                                                        >
                                                        </el-option>
                                                    </el-select>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="填报人：">
                                                    <span>{{
                                                        basicForm.preparer
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="本位币：">
                                                    <span>{{
                                                        basicForm.baseCurName
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币汇率："
                                                >
                                                    <el-input
                                                        v-model="
                                                            basicForm.baseCurRate
                                                        "
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="人民币汇率："
                                                >
                                                    <span>{{
                                                        basicForm.rmbRate
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="状态：">
                                                    <span>{{
                                                        statusLable(
                                                            basicForm.state
                                                        )
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="24">
                                                <el-form-item label="备注：">
                                                    <el-input
                                                        type="textarea"
                                                        v-model="
                                                            basicForm.remarks
                                                        "
                                                        autocomplete="off"
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 汇总明细 -->
                    <div id="planDetailCon" class="con">
                        <div class="tabs-title" id="planDetail">汇总明细</div>
                        <el-tabs
                            :class="'childTab ' + childTabClass"
                            tab-position="left"
                            v-model="tabsNameChild"
                            @tab-click="onChangeTab"
                        >
                            <el-tab-pane
                                label="按申报机构汇总"
                                name="materialDetails"
                                :disabled="clickTabFlag"
                            ></el-tab-pane>
                            <el-tab-pane
                                label="物资汇总"
                                name="technicalParameter"
                                :disabled="clickTabFlag"
                            ></el-tab-pane>
                            <div>
                                <div id="planDetailCon">
                                    <div
                                        class="tabs-title"
                                        id="materialDetails"
                                    >
                                        按申报机构汇总
                                    </div>
                                    <div class="e-table">
                                        <div class="top">
                                            <div class="left">
                                                <div>
                                                    <el-button
                                                        size="mini" class="btn-blue"
                                                        @click="selectUnit"
                                                        >选择申报单位</el-button
                                                    >
                                                    <el-button
                                                        size="mini" class="btn-delete"
                                                        @click="deleteMaterials"
                                                        >删除</el-button
                                                    >
                                                </div>
                                            </div>
                                        </div>
                                        <el-table
                                            class="table"
                                            :data="OrgtableData"
                                            border
                                            style="width: 100%"
                                            @row-click="rowClick"
                                            :row-style="rowStyle"
                                            :row-class-name="tableRowClassName"
                                            :header-cell-style="{
                                                textAlign: 'center'
                                            }"
                                            :cell-style="{
                                                textAlign: 'center'
                                            }"
                                            @selection-change="planTableSelect"
                                        >
                                            <el-table-column
                                                type="selection"
                                                width="55"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="annualDemandPlanBillNo"
                                                label="年度需用计划编号"
                                                min-width="300"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="orgName"
                                                label="机构名称"
                                                min-width="300"
                                            >
                                            </el-table-column>
                                        </el-table>

                                        <!-- 子列表 -->
                                        <div
                                            class="top"
                                            style="margin-top: 20px"
                                        >
                                            <div class="left">
                                                <div>
                                                    <el-button
                                                        size="mini" class="btn-blue"
                                                        @click="selectDetails"
                                                        >选择明细</el-button
                                                    >
                                                </div>
                                            </div>
                                        </div>
                                        <el-table
                                            class="table"
                                            :data="OrgSonTableData"
                                            border
                                            v-if="show"
                                            style="
                                                width: 100%;
                                                margin-top: 20px;
                                            "
                                            :row-class-name="tableRowClassName"
                                            :header-cell-style="{
                                                textAlign: 'center'
                                            }"
                                            :cell-style="{
                                                textAlign: 'center'
                                            }"
                                            @selection-change="planTableSelect"
                                            :tree-props="{
                                                children: 'children',
                                                hasChildren: 'hasChildren'
                                            }"
                                            default-expand-all
                                            row-key="uuid"
                                        >
                                            <el-table-column
                                                label="操作"
                                                fixed
                                                width="100px"
                                                align="left"
                                            >
                                                <template slot-scope="{ row, $index }">
                                                    <i
                                                        class="el-icon-delete"
                                                        style="
                                                            cursor: pointer;
                                                            font-size: 20px;
                                                        "
                                                        :class="{
                                                            'icon-delete-active-color':
                                                                MouseEnterId ==
                                                                row.dtlId
                                                        }"
                                                        @click="deleteEle(row,'OrgSon')"
                                                        v-if="$index > 0"
                                                    ></i>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="materialClassName"
                                                label="物资类别"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="materialName"
                                                label="物资名称"
                                                min-width="150"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="spec"
                                                label="规格型号"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="unit"
                                                label="计量单位"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="texture"
                                                label="材质"
                                                min-width="150"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="quantity"
                                                label="计划数量"
                                                min-width="150"
                                            >
                                                <template
                                                    slot-scope="{ row, $index }"
                                                >
                                                    <span v-if="$index > 0">
                                                        {{ row.quantity }}
                                                    </span>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="approvalQuantity"
                                                label="核准数量"
                                                width="150"
                                            >
                                                <template
                                                    slot-scope="{ row, $index }"
                                                >
                                                    <div
                                                        class="
                                                            history-update-tab
                                                        "
                                                    >
                                                        <el-input
                                                            @input="
                                                                countInput(row)
                                                            "
                                                            v-enter-integer1="{
                                                                set: row,
                                                                key: 'approvalQuantity'
                                                            }"
                                                            v-model="
                                                                row.approvalQuantity
                                                            "
                                                            clearable
                                                            v-if="$index > 0"
                                                            @blur="
                                                                createHistory(
                                                                    row,
                                                                    'approvalQuantity'
                                                                )
                                                            "
                                                        ></el-input>
                                                        <historyUpdateTable
                                                            v-if="
                                                                row.approvalQuantityIsUpdate ===
                                                                1
                                                            "
                                                            @clickIcon="
                                                                clickIcon(
                                                                    row.dtlId,
                                                                    'approvalQuantity'
                                                                )
                                                            "
                                                            :historyTable="
                                                                historyTableData
                                                            "
                                                        />
                                                    </div>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="approvalPrice"
                                                label="核准单价（元）"
                                                width="130"
                                            >
                                                <template
                                                    slot-scope="{ row, $index }"
                                                >
                                                    <div
                                                        class="
                                                            history-update-tab
                                                        "
                                                    >
                                                        <el-input
                                                            type="number"
                                                            @input="
                                                                countInput(row)
                                                            "
                                                            v-model="
                                                                row.approvalPrice
                                                            "
                                                            clearable
                                                            v-if="$index > 0"
                                                            v-enter-float="{
                                                                set: row,
                                                                key: 'changePrice'
                                                            }"
                                                            @blur="
                                                                createHistory(
                                                                    row,
                                                                    'approvalPrice'
                                                                )
                                                            "
                                                        ></el-input>
                                                        <historyUpdateTable
                                                            v-if="
                                                                row.approvalPriceIsUpdate ===
                                                                1
                                                            "
                                                            @clickIcon="
                                                                clickIcon(
                                                                    row.dtlId,
                                                                    'approvalPrice'
                                                                )
                                                            "
                                                            :historyTable="
                                                                historyTableData
                                                            "
                                                        />
                                                    </div>
                                                </template>
                                            </el-table-column>

                                            <el-table-column
                                                prop="approvalAmount"
                                                label="金额（元）"
                                                width="130"
                                            >
                                                <template slot-scope="{ row }">
                                                    <span>
                                                        {{ row.approvalAmount }}
                                                    </span>
                                                </template>
                                            </el-table-column>
                                            <!-- <el-table-column
                        prop="purchasingUnitName"
                        label="集中采购单位"
                        width="150"
                      >
                      <template slot-scope="{ row,$index }">
                      <el-input
                      v-if="$index > 0"
                      v-model="row.purchasingUnitName">
                         <i slot="suffix" class="el-icon-document-copy" @click="clickPurchasingUnit(row)"></i>
                      </el-input>

                      </template>
                      </el-table-column> -->

                                            <el-table-column
                                                prop="purchasingUnitName"
                                                width="150"
                                            >
                                                <!-- 录入人可选择，审核中也可由审核人核准数据为准，单选，弹窗选择全集团组织机构数据，支持批量选择。 -->
                                                <template slot="header">
                                                    <span>集中采购单位</span>
                                                    <i
                                                        slot="suffix"
                                                        class="
                                                            el-input__icon
                                                            el-icon-document-copy
                                                        "
                                                        style="cursor: pointer"
                                                        @click="
                                                            selectPurchasingUnitName
                                                        "
                                                    ></i>
                                                </template>
                                                <template
                                                    slot-scope="{ row, $index }"
                                                >
                                                    <el-input
                                                        @input="input(row)"
                                                        v-model="
                                                            row.purchasingUnitName
                                                        "
                                                        v-if="$index > 0"
                                                    >
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            style="
                                                                cursor: pointer;
                                                            "
                                                            @click="
                                                                clickPurchasingUnit(row)
                                                            "
                                                        ></i>
                                                    </el-input>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="procurementMethod"
                                                label="采购方式"
                                                width="150"
                                            >
                                                <template slot-scope="{ row,$index  }">
                                                    <el-select v-model="row.procurementMethod" placeholder="请选择" v-if="$index > 0" @change="selectProcurementMethodTwo(row)">
                                                        <el-option
                                                            v-for="item in procurementMethod"
                                                            :key="item.value"
                                                            :label="item.label"
                                                            :value="item.value">
                                                        </el-option>
                                                    </el-select>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="contractorName"
                                                label="承建单位"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="remarks"
                                                label="备注"
                                                width="100"
                                            >
                                            </el-table-column>
                                        </el-table>
                                        <div
                                            class="errorMsg"
                                            v-if="errorMsg.length > 0"
                                        >
                                            <span
                                                v-for="(
                                                    item, index
                                                ) in errorMsg"
                                                :key="index"
                                            >
                                                {{ item }}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div id="planDetailCon">
                                    <div
                                        class="tabs-title"
                                        id="technicalParameter"
                                    >
                                        物资汇总
                                    </div>
                                    <div class="e-table">
                                        <el-table
                                            class="table"
                                            :header-cell-style="{
                                                textAlign: 'center'
                                            }"
                                            :cell-style="{
                                                textAlign: 'center'
                                            }"
                                            :data="materialsTableData"
                                            border
                                            style="width: 100%"
                                            :row-class-name="tableRowClassName"
                                            @selection-change="planTableSelect"
                                            :tree-props="{
                                                children: 'children',
                                                hasChildren: 'hasChildren'
                                            }"
                                            default-expand-all
                                            row-key="uuid"
                                        >
                                            <el-table-column
                                                label="操作"
                                                fixed
                                                width="100px"
                                                align="left"
                                            >
                                                <template
                                                    slot-scope="{ row, $index }"
                                                >
                                                    <i
                                                        class="el-icon-delete"
                                                        style="
                                                            cursor: pointer;
                                                            font-size: 20px;
                                                        "
                                                        :class="{
                                                            'icon-delete-active-color':
                                                                MouseEnterId ==
                                                                row.dtlId
                                                        }"
                                                        @click="deleteEle(row,'materials')"
                                                        v-if="$index > 0"
                                                    ></i>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="materialClassName"
                                                label="物资类别"
                                                width="150"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="materialName"
                                                label="物资名称"
                                                min-width="200"
                                            >
                                                <template slot-scope="scope">
                                                    <span
                                                        @click="
                                                            showA(scope.row)
                                                        "
                                                        style="
                                                            color: blue;
                                                            cursor: pointer;
                                                        "
                                                    >
                                                        {{
                                                            scope.row
                                                                .materialName
                                                        }}
                                                    </span>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="spec"
                                                label="规格型号"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="unit"
                                                label="计量单位"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="texture"
                                                label="材质"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="planQuantity"
                                                label="计划数量"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="planPrice"
                                                label="单价（元）"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="amount"
                                                label="金额（元）"
                                                width="100"
                                            >
                                            </el-table-column>

                                            <el-table-column
                                                prop="purchaseType"
                                                label="采购方式"
                                                width="150"
                                            >
                                                <template slot-scope="{ row,$index  }">
                                                    <el-select v-model="row.procurementMethod" placeholder="请选择" v-if="$index > 0" @change="selectProcurementMethodTwo(row)">
                                                        <el-option
                                                            v-for="item in procurementMethod"
                                                            :key="item.value"
                                                            :label="item.label"
                                                            :value="item.value">
                                                        </el-option>
                                                    </el-select>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="purchasingUnitName"
                                                label="集中采购单位"
                                                min-width="150"
                                            >
                                                <template
                                                    slot-scope="{ row, $index }"
                                                >
                                                    <el-input
                                                        @input="input(row)"
                                                        v-model="
                                                            row.purchasingUnitName
                                                        "
                                                        v-if="$index > 0"
                                                    >
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            style="
                                                                cursor: pointer;
                                                            "

                                                        ></i>
                                                    </el-input>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                        <!-- 机构汇总表 -->
                                        <el-table
                                            class="table"
                                            :data="materialsNameData"
                                            border
                                            style="
                                                width: 100%;
                                                margin-top: 20px;
                                            "
                                            :cell-class-name="cellClsNm"
                                            :header-cell-style="{
                                                textAlign: 'center'
                                            }"
                                            :cell-style="{
                                                textAlign: 'center'
                                            }"
                                        >
                                            <el-table-column
                                                prop="orgName"
                                                label="机构名称"
                                                min-width="200"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="materialName"
                                                label="物资名称"
                                                min-width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="spec"
                                                label="规格型号"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="unit"
                                                label="计量单位"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="texture"
                                                label="材质"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="planQuantity"
                                                label="计划数量"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="planQuantity"
                                                label="市场单价（元）"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="budgetAmount"
                                                label="金额（元）"
                                                width="100"
                                            >
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </div>
                            </div>
                        </el-tabs>
                    </div>
        <span>{{test}}</span>

                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="turnover"
                        />
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <div class="e-table">
                                <ComAuditHistoryIndex
                                    :billType="6087"
                                    ref="AuditHistoryRef"
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <span class="tip"
                ><span style="color: red; margin-right: 0">*</span
                >为必填项</span
            >
            <el-button
                type="primary"
                class="btn-blue"
                @click="submitCommit"
                size="small"
                >保存并提交</el-button
            >
            <el-button
                type="primary"
                class="btn-blue"
                @click="submit"
                size="small"
                >保存</el-button
            >
            <el-button
                slot="reference"
                type="primary"
                class="btn-delete"
                @click="clickDel"
                v-if="auditState.canModify"
                size="small"
                >删除</el-button
            >
            <!-- <ComExaButtons :auditState="auditState" @exas="exas" v-if="statusLable(formData.planConfiguration.state) !== '已作废'"/> -->
            <el-button size="small" @click="handleClose">取消</el-button>

        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import { showSuccessPop, getUuid } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import planRequest from '@/api/turnover/plan.js'
import { selectDataClient, openAppClient } from '@/utils/common'
import { getRmbRate } from '@/api/equip/common.js'

import auditRequest from '@/api/turnover/audit.js'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'
import historyUpdateTable from '@/components/common/historyUpdateTable'
import { removeRepetition } from '@/api/equip/popupCallback.js'
import { hideLoading } from '@/utils/common'

export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        historyUpdateTable
    },
    data () {
        return {
            test: [],
            ress: '',
            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6087,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            tabsName: 'baseInfo',
            userName: '',
            clickId: 'baseInfo',
            tabsNameChild: '',
            childTabClass: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },

            OrgtableData: [], //申报机构数据
            OrgSonTableData: [], //申报机构子列表
            materialsTableData: [], //物资汇总数据
            auditHistoryList: [], //审核历史
            planSelect: [], //申报机构表格明细选择项
            value: '',
            textarea: '',
            formData: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            MouseEnterId: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicForm: {
                amount: 0,
                baseCurAmount: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: 0,
                billId: '',
                billNo: '',
                currency: '',
                currencyId: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                preparer: '',
                preparerId: '',
                remarks: '',
                rmbAmount: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                sourceType: 0,
                state: 0,
                summaryDate: '',
                workId: ''
            },
            objFlag: {
                flag5: false
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            billId: '',
            isSkip: false, //是否跳转
            show: true, //申报机构子列表
            dtlIds: '', //
            //验证
            rules: {
                summaryDate: [
                    {
                        required: true,
                        message: '请输入汇总日期',
                        trigger: 'blur'
                    }
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'chenge' }
                ]
            },
            showBaseCurName: false,
            materialsNameData: [], //机构汇总表
            createHistoryData: [], //明细修改历史列表
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            onlyID: '', //判断选择那行的唯一id
            procurementMethod: [{
                value: 0,
                label: '邀请招标'
            }, {
                value: 1,
                label: '公开招标'
            }, {
                value: 2,
                label: '询价'
            }, {
                value: 3,
                label: '竞争性谈判'
            }, {
                value: 4,
                label: '单一性来源'
            },
            {
                value: 5,
                label: '甲控（业主招标）'
            }],
            annualDemandPlanBillIdArr: [], //申年度计划IDs
            itemObj: {}, //物资汇总去重
        }
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.userId = localStorage.getItem('userId')
        this.basicForm.operator = localStorage.getItem('userName')
        this.billId = this.$route.query.billid

        this.initData()
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    methods: {
        ...mapMutations([
            'setPopConfirm',
            'setSelectedInfo',
            'setHistoryTableData'
        ]),

        initData () {
            this.getCurrentUnitInfo()
            this.getTurnoverCentralizedPurchaseSummaryGetAgencyListByBillId()
            this.getBasicData()
            this.getTurnoverCentralizedPurchaseSummaryGetSummarySetting() //回去物资汇总明细
        },
        //跳转到明细
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },

        //获取按钮状态
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //根据周材集采汇总id查询申报机构
        getTurnoverCentralizedPurchaseSummaryGetAgencyListByBillId () {
            planRequest
                .turnoverCentralizedPurchaseSummaryGetAgencyListByBillId(
                    this.billId
                )
                .then(res => {
                    this.OrgtableData = res
                    // this.rollUp(res)
                })
        },

        //根据周材集采汇总id查询申报机构
        getTurnoverCentralizedPurchaseSummaryGetSummarySetting () {
            planRequest
                .turnoverCentralizedPurchaseSummaryGetSummarySetting(
                    this.billId
                )
                .then(res => {
                    console.log(res, '当前打印')
                    // this.OrgtableData = res
                    // this.notSetData = JSON.parse(JSON.stringify(res)) //没去重之前的数据
                    // //去重
                    let children = []
                    res.forEach(item => {
                        item.children.forEach(a => {
                            children.push(a)
                        })
                    })
                    var result = []
                    var obj = {}
                    for (var i = 0; i < children.length; i++) {
                        if (children[i].materialId in obj) {
                            // 相同时肯定不push
                            if (
                                obj[children[i].materialId] !==
                                children[i].texture
                            ) {
                                // 不相同时，判断是否是 '' 和 null，如果是，则表示重复
                                if (
                                    !(
                                        !obj[children[i].materialId] &&
                                        !children[i].texture
                                    )
                                ) {
                                    // 当都不是 '' 和 null 时，才表示不重复，此时才push
                                    result.push(children[i])
                                }
                            }
                        } else {
                            obj[children[i].materialId] = children[i].texture
                            result.push(children[i])
                        }
                        // obj[children[i].amount] = 1
                    }
                    res.forEach(item => {
                        item.uuid = getUuid()

                        item.materialClassName = item.topClassName
                        item.children = result
                        item.children.forEach(v => {
                            v.uuid = getUuid()
                            v.parentId = item.uuid
                            v.amount = null
                        })
                    })
                    console.log(result, 'datadata')
                    this.materialsTableData = res
                })
        },
        //币种切换
        currencyChange (val) {
            this.basicForm.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种
            if (this.basicForm.currency === '人民币') {
                this.basicForm.rmbRate = 1
            } else {
                getRmbRate({
                    //获取机构下某币种的人民币汇率
                    currency: val,
                    orgId: this.userInfo.orgInfo.orgId
                })
                    .then(res => {
                        this.basicForm.rmbRate = res.rate
                    })
                    .catch(() => {})
            }
            if (this.basicForm.currencyId === this.basicForm.baseCurId) {
                //币种=本位币
                this.basicForm.baseCurRate = 1
                this.showBaseCurName = false
            } else {
                this.basicForm.baseCurRate = null
                this.showBaseCurName = true
            }
        },

        //向上汇总
        rollUp (res) {
            res.forEach(item => {
                //拿到 数据 汇总计划金额
                this.basicForm.amount += Number(item.totalAmount)
            })
        },
        //点击图标的时候 获取历史记录
        clickIcon (dtlId, column) {
            this.setHistoryTableData([])
            alert(dtlId)
            planRequest
                .turnoverAnnualDemandPlanGetHistoryList(
                    dtlId,
                    column,
                    this.auditParams.billType
                )
                .then(res => {
                    this.historyTableData = res
                    this.setHistoryTableData(res)
                })
                .catch(e => {
                    alert(e.message)
                })
        },
        // 编辑的时候造历史修改数据结构
        createHistory (row, e) {
            if (row.dtlId) {
                this.createHistoryData.push({
                    historyId: '',
                    modifedName: '',
                    modifiedDate: '',
                    modifiedId: '',
                    opinion: '',
                    sourceId: row.dtlId,
                    sourceValue: 0,
                    updateColumn: e, //修改字段
                    updatedValue: row[e] //修改后的值
                })
            }
        },
        /**
         * 下边几个按钮
         */
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.basicForm.validate(valid => {
                    if(valid) {
                        planRequest
                            .turnoverCentralizedPurchaseSummaryUpdate(
                                this.basicForm
                            )
                            .then(() => {
                                resolve()
                            })
                            .catch(err => {
                                reject(err)
                                this.setError('baseInfo')
                                this.scorllError()
                            })
                    }else{
                        reject()
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新汇总明细
        updateDetailInfo () {
            return new Promise((resolve, reject)=>{
                const data = JSON.parse(JSON.stringify(this.OrgtableData))
                this.verifyTable().then(()=>{
                    planRequest .turnoverCentralizedPurchaseSummaryUpdateDtlList(data)
                        .then(() => {
                            resolve()
                        })
                        .catch(err => {
                            reject(err)
                            this.setError('planDetail')
                            this.scorllError()
                        })
                }).catch(err=>{
                    this.setError('planDetail')
                    reject(err)
                    this.scorllError()
                })
            })
        },
        //更新物资汇总
        updateMaterialsDetailInfo () {
            return new Promise((resolve, reject)=>{
                planRequest.turnoverCentralizedPurchaseSummarySaveSummarySetting( this.materialsTableData )
                    .then(() => {
                        resolve()
                    })
                    .catch(err => {
                        reject(err)
                        this.setError('technicalParameter')
                        this.scorllError()
                    })
            })
        },
        //保存按钮
        submit () {
            this.errorList = []
            Promise.all([
                this.updateBaseInfo(),
                this.updateDetailInfo(),
                this.updateMaterialsDetailInfo()
            ])
                .then(() => {
                    this.clientPop('suc', '保存成功')
                })
                .finally(() => {
                    hideLoading()
                })
            // this.$refs['basicForm'].validate(valid => {
            //     if (valid) {
            //         const data = JSON.parse(JSON.stringify(this.OrgtableData))
            //         if (!data.length) {
            //             this.clientPop('err', '请选择申报机构!')
            //             return
            //         }
            //         // 明细非空验证
            //         this.verifyTable()
            //         if (this.isErrorMsg) {
            //             return
            //         }
            //         return new Promise((resolve, reject) => {
            //             planRequest
            //                 .turnoverCentralizedPurchaseSummaryUpdateDtlList(
            //                     data
            //                 )
            //                 .then(res => {
            //                     resolve(res)
            //                     showSuccessPop('保存明细成功！', this.initData)
            //                 })
            //                 .catch(err => {
            //                     reject(err)
            //                 })
            //             if (this.isCollect) {
            //                 //初次进入页面 点击了申报单位之后的回调
            //                 const resource = []
            //                 data.forEach(item => {
            //                     if (item.dtls) {
            //                         item.dtls.forEach(v => {
            //                             v.children.forEach(n => {
            //                                 n.billId = this.billId
            //                             })
            //                             resource.push(v)
            //                         })
            //                     }
            //                 })
            //                 planRequest
            //                     .turnoverCentralizedPurchaseSummarySaveSummarySetting(
            //                         resource
            //                     )
            //                     .then(res => {
            //                         resolve(res)
            //                         showSuccessPop(
            //                             '保存物资汇总成功！',
            //                             this.initData
            //                         )
            //                     })
            //                     .catch(err => {
            //                         reject(err)
            //                     })
            //             }

            //             //修改基础信息
            //             planRequest
            //                 .turnoverCentralizedPurchaseSummaryUpdate(
            //                     this.basicForm
            //                 )
            //                 .then(res => {
            //                     resolve(res)
            //                     showSuccessPop('保存基础成功！', this.initData)
            //                 })
            //                 .catch(err => {
            //                     reject(err)
            //                 })
            //         })
            //     }
            // })
        },

        // 保存并提交
        submitCommit () {
            const data = JSON.parse(JSON.stringify(this.OrgtableData))
            if (!data.length) {
                this.clientPop('err', '请选择申报机构!')
                return
            }
            this.verifyTable()
            if (this.isErrorMsg) {
                return
            }
            // let promise1 = planRequest.turnoverCentralizedPurchaseSummaryUpdate(
            //     this.basicForm
            // )
            // const promise2 = planRequest
            //     .turnoverCentralizedPurchaseSummaryUpdateDtlList(data)
            //     .then()
            Promise.all([this.updateBaseInfo, this.updateDetailInfo, this.updateMaterialsDetailInfo]).then(() => {
                auditRequest.commit(this.auditParams).then(() => {
                    this.clientPop('suc', '保存并提交成功', this.handleClose)
                })
            })
        },
        //计划明细非空验证
        verifyTable () {
            return  new Promise((resolve, reject)=>{
                this.errorMsg = []
                if (this.OrgtableData.length > 0) {
                    this.OrgtableData.forEach((n, index) => {
                        if (n.dtls) {
                            n.dtls.forEach(v => {
                                v.children.forEach(item => {
                                    if (item.changeType !== -1) {
                                        if (item.approvalQuantity === '' || item.approvalQuantity === null) {
                                            let str = `请填写第 ${index + 1} 行的核准数量`
                                            this.errorMsg.push(str)
                                        }
                                        if (item.approvalPrice === '' || item.approvalPrice === null) {
                                            let str = `请填写第 ${index + 1} 行的核准单价`
                                            this.errorMsg.push(str)
                                        }
                                    }
                                })
                            })
                        }
                    })
                }
                if(this.errorMsg.length > 0) {
                    reject()
                }else{
                    resolve()
                }
            })
        },
        nullify () {
            //作废
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                auditRequest.nullify(auditParams).then(() => {
                    this.clientPop('suc', '作废成功')
                    this.getCurrentUnitInfo()
                })
            })
        },
        //把子列表的数据合并到this.OrgtableData的children
        DoMaterialsTableData () {
            this.OrgtableData.forEach(item => {
                item.changeType = 1
                item.billId = this.billId
            })
        },

        //点击选择 选择申报单位 获取申报机构
        selectUnit () {
            // 弹窗选择数据
            let ids = []
            ids = this.OrgtableData.map(x=>x.annualDemandPlanBillId)
            selectDataClient({
                SelectServiceToken:
                    '/turnover/centralizedPurchaseSummary/getAgencyList', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    // 'keyWord': '',
                    // 'limit': 10,
                    // 'page': 1,
                    // 'planId': this.basicForm.annualDemandPlanBillId
                    // id: '0'
                }), // 接口参数(name为模拟参数)
                Title: '选择申报单位' // 标题
            }).then(val => {
                const newArr = []
                this.annualDemandPlanBillIdArr = []
                val.forEach(item => {
                    item.annualDemandPlanBillId = item.billId
                    item.annualDemandPlanBillNo = item.billNo
                    newArr.push(item.billId)
                })
                planRequest
                    .turnoverCentralizedPurchaseSummaryGetAgencyListByOrgId(
                        newArr
                    )
                    .then(res => {
                        this.test = res
                        res.forEach(item => {
                            item.changeType = 1
                            item.billId = this.billId
                            this.annualDemandPlanBillIdArr.push(item.annualDemandPlanBillId)
                            this.OrgtableData.push(item)
                        })
                        //去重
                        this.OrgtableData = removeRepetition({
                            'arr': this.OrgtableData,
                            'id': 'annualDemandPlanBillId'
                        })
                        this.isCollect = true
                        this.materialsTableDataAarry()
                    })
            })
        },
        //根据总计划billid集合获取总计划明细集合
        materialsTableDataAarry () {
            planRequest.turnoverCentralizedPurchaseSummaryGetAllMaterial(this.annualDemandPlanBillIdArr)
                .then(res => {
                    this.itemObj = {}
                    let count = 0
                    res.forEach(item=>{
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(v => {
                            v.uuid = getUuid()
                            //汇总小计
                            count += v.amount
                            item.materialName = `小计： ${count}`
                        })
                        //去重
                        item.children = item.children.reduce((item, next)=>{
                            if(next.changeType == -1) {
                                item.push(next)
                            }else{
                                //物资类别id  物资id  材质去重
                                if(!this.itemObj[next.materialClassId] || !this.itemObj[next.materialId] || !this.itemObj[next.texture]) {
                                    item.push(next)
                                    this.itemObj[next.materialClassId] = true
                                    this.itemObj[next.materialId] = true
                                    this.itemObj[next.texture] = true
                                }
                            }
                            return item
                        }, [])
                    })
                    this.materialsTableData = res
                })
        },
        //判读选择中的是那行 年度需用计划编号
        rowClick (row) {
            if (row.changeType == 1) {
                planRequest.turnoverCentralizedPurchaseSummaryGetAllMaterial([row.annualDemandPlanBillId])
                    .then(res => {
                        let count = 0
                        this.OrgSonTableData = res
                        this.OrgSonTableData.forEach(item => {
                            item.changeType = 1
                            item.uuid = getUuid()
                            item.materialClassName = item.topClassName
                            item.children.forEach(v => {
                                this.count_(v, 1)
                                //汇总小计
                                count += Number( v.approvalAmount)
                                item.materialName = `小计： ${count}`
                                v.changeType = 1
                                v.parentId = item.uuid
                                v.uuid = getUuid()
                            })
                            row.dtls.push(item)
                        })
                    })
            } else {
                planRequest
                    .turnoverCentralizedPurchaseSummaryGetMaterial(
                        row.dtlId
                    )
                    .then(res => {
                        res.forEach(item => {
                            item.uuid = getUuid()
                            item.materialClassName = item.topClassName
                            // row.dtls.push(item)
                            item.children.forEach(v => {
                                this.count_(v, 2)
                                v.changeType = 2
                                v.parentId = item.uuid
                                v.uuid = getUuid()
                            })
                        })
                        this.OrgSonTableData = res

                    })
            }
            if(this.onlyID === row.annualDemandPlanBillId) return
            this.onlyID = row.annualDemandPlanBillId
        },
        //选择行颜色
        rowStyle ({ row }) {
            if(!this.onlyID)return
            if(this.onlyID === row.annualDemandPlanBillId) {
                return {
                    'background-color': 'rgb(179,210,238)!important'
                }
            }
        },
        //选择物资汇总的采购方式
        selectProcurementMethodTwo (row) {
            row.changeType = 2
            console.log('row.changeType', row.changeType)
            this.OrgtableData.forEach(item=>{
                if(item.billId ===  row.billId) {
                    item.changeType = 2
                    item.children.forEach(a=>{
                        a.children.forEach(b=>{
                            b.procurementMethod = row.procurementMethod
                            b.changeType = 2
                        })
                    })
                }
            })
            this.OrgSonTableData.forEach(item=>{
                item.changeType = 2
                item.children.forEach(a=>{
                    if(a.billId === row.billId) {
                        a.procurementMethod = row.procurementMethod
                        a.changeType = 2
                    }
                })
            })
        },
        // 点击子表的选择明细
        selectDetails () {
            console.log('选择明细')
        },
        //申报机构选择集中采购单位  批量选择
        selectPurchasingUnitName () {
            console.log(this.OrgSonTableData)
            const val =  [{ 'orgId': '1439990096827777024', 'orgName': '四川公路桥梁建设集团有限公司江习古高速公路项目经理部TJ4分部', 'shortCode': 'SRBGJXGGS004', 'orgType': '5', 'parentId': '1439990097054269442', 'parentName': '四川公路桥梁建设集团有限公司公路隧道分公司' }]
            // val
            this.OrgSonTableData.forEach(a => {
                a.changeType = 2
                a.children.forEach(c => {
                    c.purchasingUnitId = val[0].orgId
                    c.purchasingUnitName = val[0].orgName
                    c.changeType = 2
                })
            })
            // selectDataClient({
            //     SelectServiceToken: '/hr/org/getAllOrgPage', // 客户端对应方法名
            //     IsSingleMode: true, // 是否单选 true 单选 false 多选
            //     SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
            //     Title: '选择机构' // 标题
            // }).then(val => {
            //     this.OrgtableData.forEach(a => {
            //         a.changeType = 2
            //         if (a.dtls) {
            //             a.dtls.forEach(b => {
            //                 b.children.forEach(c => {
            //                     c.purchasingUnitId = val[0].orgId
            //                     c.purchasingUnitName = val[0].orgName
            //                     c.changeType = 2
            //                 })
            //             })
            //         }
            //     })
            // })
        },
        //点击集中采购单位 选择单位

        clickPurchasingUnit (row) {
            console.log(row)
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/hr/org/getChildrenOrg', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                Title: '选择全集团组织机构数据', // 标题
                InitParamsStr: JSON.stringify({ orgId: this.basicForm.orgId }) //参数
            }).then(val => {
                const orgData = val[0] //获取客户端返回的数据
                row.purchasingUnitId = orgData.orgId
                row.purchasingUnitName = orgData.orgName
                row.changeType === 1
                    ? this.count_(row, 1)
                    : this.count_(row, 2) //判断当前的状态是新增还是修改
                // 保存用户选择返回数据到store
                this.setSelectedInfo(val)
                // 客户端弹窗预览结果
                // 参数依次为: 打开页面地址、标题、回调函数
                openAppClient('/showSelectedData', '选择结果', function () {})
            })
        },
        //点击物资汇总的物资名称，汇总物资下的所有机构
        showA (row) {
            console.log(row, 'row')
            console.log(this.notSetData, 'this.notSetData')
            this.materialsNameData = []
            this.notSetData.forEach(item => {
                item.children.forEach(b => {
                    if (row.materialId === b.materialId) {
                        // const obj = {
                        //     orgName: item.orgName,
                        //     materialName: b.materialName,
                        //     spec: b.spec,
                        //     unit: b.unit,
                        //     texture: b.texture,
                        //     planQuantity: b.planQuantity,
                        //     marketPrice: '',
                        //     amount: b.amount
                        // }
                        // this.materialsNameData = []
                        this.materialsNameData.push(b)
                    }
                })
            })
        },
        //申报机构汇总-删除 申报机构汇总表格明细
        deleteMaterials () {
            // this.annualDemandPlanBillIdArr = []
            if (this.planSelect.length > 0) {
                this.OrgtableData.forEach(v => {
                    this.planSelect.forEach(item => {
                        if (item.dtlId && item.dtlId === v.dtlId) {
                            v.changeType = -1
                        }
                    })
                })
            }
            if (this.planSelect.length > 0) {
                this.planSelect.forEach(item => {
                    if (item.dtlId) {
                        const newArr = []
                        newArr.push(item)
                        newArr.forEach(item => {
                            this.$set(item, 'changeType', -1)
                        })
                        // this.$refs.multipleTable.clearSelection()
                    } else {
                        const localArr = []
                        localArr.push(item)
                        for (let i = this.OrgtableData.length; i > 0; i--) {
                            for (let j = 0; j < localArr.length; j++) {
                                if (this.OrgtableData[i - 1] === localArr[j]) {
                                    this.OrgtableData.splice(i - 1, 1)
                                }
                            }
                        }
                        // this.$refs.multipleTable.clearSelection()
                    }
                })
            }
            //清空子列表的数据
            this.OrgSonTableData.forEach(item => {
                item.changeType = -1
                item.children.forEach(v=>{
                    v.changeType = -1
                })
            })

            //获取总计划annualDemandPlanBillId
            this.annualDemandPlanBillIdArr = this.OrgtableData.map(x=>{
                if(x.changeType !== -1) {
                    return x.annualDemandPlanBillId
                }
            })
            //根据总计划annualDemandPlanBillId集合获取总计划明细集合
            this.materialsTableDataAarry()
        },

        //监听明细 机构汇总表格 数据input事件 判断用户是否修改  ，计算金额
        countInput (row) {
            row.changeType === 1 ? this.count_(row, 1) : this.count_(row, 2)
            console.log(this.materialsTableData, '物资汇总')
        },
        // 汇总逻辑
        count_ (row, num) {
            row.changeType = num
            this.basicForm.amount = null

            row.approvalAmount = Number(row.approvalQuantity * row.approvalPrice).toFixed(2)
            this.OrgtableData.forEach(item => {
                item.changeType = num
                this.basicForm.amount += item.totalAmount = row.approvalAmount //把汇总的金额给父级 方便汇总计算
                if (item.children) {
                    item.children.forEach(i => {
                        i.changeType = num
                    })
                }
            })
        },
        //申报机构汇总-明细子列表删除按钮
        deleteEle (row, name) {
            row.changeType = -1
            switch(name) {
            case 'materials':  //物资汇总
                this.materialsTableData.forEach(item=>{
                    var count = 0
                    item.children.forEach(v=>{
                        if(v.changeType !== -1) {
                            count += Number(v.amount)
                            item.materialName = `小计： ${count}`
                        }else{
                            item.materialName = `小计： ${count}`
                        }
                    })
                })
                break
            case 'OrgSon':  //申报机构汇总
                this.OrgSonTableData.forEach(item => {
                    var count1 = 0
                    item.children.forEach(v => {
                        //汇总小计
                        if(v.changeType !== -1) {
                            count1 += Number(v.approvalAmount)
                            item.materialName = `小计： ${count1}`
                        }else{
                            item.materialName = `小计： ${count1}`
                        }
                    })
                })
                break
            }
            // this.OrgSonTableData.forEach(item => {
            //     item.changeType = 2
            //     if (item.dtls) {
            //         item.dtls.forEach(v => {
            //             if (v.children) {
            //                 const data = v.children.find(i => {
            //                     return i.dtlId === row.dtlId
            //                 })
            //                 data.changeType = -1
            //             }
            //         })
            //     }
            // })
        },
        //获取集采汇总id获取基本信息
        getBasicData () {
            planRequest
                .turnoverCentralizedPurchaseSummaryFindById(this.billId)
                .then(res => {
                    this.basicForm = res
                })
        },
        //删除提示框
        clickDel () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //根据集采汇总id删除单据
        delData () {
            planRequest
                .turnoverCentralizedPurchaseSummaryDelete(this.billId)
                .then(res => {
                    if (res.code == 200) {
                        showSuccessPop('删除成功！')
                        this.isSkip = true
                    }
                    this.$router.push('/revolveCollectList')
                })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //申报机构删除逻辑
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        //获取用户在 汇总明细-申报机构汇总 表格的已选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //取消
        handleClose () {
            this.dialogVisible = false
            this.$router.replace('./revolveCollectList')
        },
        onChangeTab (e) {
            console.log('clickTabFlag: ', this.clickTabFlag)
            $.scrollTo(`#${e.name}`, 500)
            this.clickId = e.name //记录每次点击的id
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
                        document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            popConfirm: 'popConfirm',
            popStatus: 'popStatus',
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),

        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)

                if (obj !== undefined) {
                    return obj.label
                }
            }
        }
    },

    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            ['planDetail', 'materialDetails', 'technicalParameter'],
            'accessory',
            'auditHistory'
        ]
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //当点击的tab有子tab时做滚动逻辑
            if (this.clickTabFlag && arr.find(x => x === this.clickId)) {
                this.childTabClass = '' //无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if (item instanceof Array) {
                        const prevHeight = document.getElementById(
                            item[0]
                        ).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                        arr = item.map((x, i) => {
                            if (i === 0) {
                                return document.getElementById(x).offsetTop
                            } else {
                                return (
                                    document.getElementById(x).offsetTop +
                                    prevHeight +
                                    document.getElementById(item[0]).offsetTop
                                )
                            }
                        })
                        return arr
                    } else {
                        itemTop = document.getElementById(item).offsetTop
                        return itemTop
                    }
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if ($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for (let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if (scrollTop + 1 >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if (scrollTop + 1 >= item[0]) {
                        curLocal = i
                        break
                    }
                } else {
                    let item = $idsTop[i]
                    if (scrollTop + 1 >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if (arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.tabsNameChild = arr[curLocal][curLocalChild]
            } else {
                this.tabsName = arr[curLocal]
            }
            //动态改变二级选项卡类名
            arr.forEach((item, index) => {
                if (item instanceof Array) {
                    let tabNavHeight = document.querySelector(
                        '.childTab .el-tabs__nav'
                    )
                        ? document.querySelector('.childTab .el-tabs__nav')
                            .offsetHeight
                        : 0
                    if (scrollTop + 1 >= $idsTop[index + 1] - tabNavHeight) {
                        this.childTabClass = 'childTab2'
                    } else if (scrollTop <= $idsTop[index][1]) {
                        this.childTabClass = ''
                    } else {
                        this.childTabClass = 'childTab1'
                    }
                }
            })
        })

        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if (item instanceof Array) {
                    const prevHeight = document.getElementById(
                        item[0]
                    ).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                    arr = item.map((x, i) => {
                        if (i === 0) {
                            return document.getElementById(x).offsetTop
                        } else {
                            return (
                                document.getElementById(x).offsetTop +
                                prevHeight +
                                document.getElementById(item[0]).offsetTop
                            )
                        }
                    })
                    return arr
                } else {
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })

        this.scorllDtl()
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
::v-deep.el-table .warning-row {
    display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
.childTab {
    ::v-deep .el-tabs__header {
        position: absolute !important;
    }
    ::v-deep .el-tabs__content {
        padding: 0 0 0 20px !important;
    }
}
.childTab1 {
    ::v-deep .el-tabs__header {
        position: absolute !important;
        .el-tabs__nav-scroll {
            position: relative;
            .el-tabs__nav {
                position: fixed;
                top: 0;
                width: 190px;
            }
        }
    }
}
.childTab2 {
    ::v-deep .el-tabs__header {
        position: absolute !important;
        .el-tabs__nav-scroll {
            position: relative;
            .el-tabs__nav {
                position: absolute;
                bottom: 0;
                width: 100%;
            }
        }
    }
}
</style>
